package net.esj.basic.expression.formula;


public class Calculator {

	public static final Formula[] EMPTY_FORMULAS = new Formula[0];
	
	private Formula[] formulas = EMPTY_FORMULAS;

	private Calculator(){}
	
	public static Calculator newInstance(){ 
		return new Calculator();
	}
	
	public Number calc(){
		Number n = 0;
		for(Formula f : formulas){
			 n = f.calc(n);
		}
		return n;
	}
	
	public Calculator addFormula(FormulaExpression exp , Number value){
		if(formulas==null || formulas == EMPTY_FORMULAS){
			formulas = new Formula[1];
		}else{
			int len = formulas.length;
			Formula[] tmp = new Formula[len + 1];
			System.arraycopy(formulas, 0, tmp, 0, len);
			tmp[len] = null;
			formulas = tmp;
		}
		switch(exp){
		case ADD:
			formulas[formulas.length-1] = new AddFormula(value);
			break;
		case DIV:
			formulas[formulas.length-1] = new DivFormula(value);
			break;
		case MULT:
			formulas[formulas.length-1] = new MultFormula(value);
			break;
		case SUB:
			formulas[formulas.length-1] = new SubFormula(value);
			break;
		case NULL:
			formulas[formulas.length-1] = new SetFormula(value);
			break;
		}
		return this;
	}
	
	
}
